<?php

include_once(dirname(__FILE__). '/OController.php');

class PaymentController extends OController {
	public $defaultAction = 'rates';
	
	public $menu = array(
		array('label' => 'Payment Rates', 'url' => array('owner/payment/rates')),
		array('label' => 'Unpaid Balance', 'url' => array('owner/payment/balance')),
		array('label' => 'Payment History', 'url' => array('owner/payment/history')),
		array('label' => 'Edit Payment Info', 'url' => array('owner/account/update?fields=payment'))
	);
	
	/**
	 * 佣金支付比例的相关文字信息
	 */
	public function actionRates() {
		$order_historys = OrderHistory::model()->findAll();
		
		$this->render('rates');
	}
	
	/**
	 * 网站主提交付款请求
	 */
	public function actionRequest() {
		if (!empty($_POST['ajax']) && $_POST['ajax']=='payment-request') {
			if (PaymentRequest::hasSent(Yii::app()->user->id)) {
				echo json_encode(array("result" => false));
			} else {
				$payment_request = new PaymentRequest();
				$payment_request->attributes = array(
					'owner_id' => Yii::app()->user->id,
					'amount' => $_POST['amount'],
					'adddate' => date('Y-m-d'),
					'status' => 0
				);
				$payment_request->save();
				echo json_encode(array("result" => true));
			}
		}
	}
	
	/**
	 * 查看加盟账号的佣金余额
	 * 佣金的计算方法，目前有两种：
	 * - Per First Order and Lead 
	 *   这是首次订单和按会员注册结合的佣金支付方式，在此方式下，
	 *   佣金总额 = 首次订单总额   X 佣金比例  + 会员注册数  X 每个会员给付的佣金
	 *   其中，首次订单的佣金比例目前是 30%，每个注册会员给付的佣多是 $2
	 * - Per Lead
	 *   按注册会员支付佣金
	 *   对于第 1~59 个注册会员，每个给付 $3
	 *   对于第 60~149个注册会员，每个给付 $4
	 *   对于150个以后的会员，每个给付 $5
	 */
	public function actionBalance() {
		$result = QpidBalance::activeCount(Yii::app()->user->id);
		$data = array(
			'dataProvider' => QpidBalance::getDataProvider(Yii::app()->user->id, $result['program']),
			'balance' => $result['balance']
		);
		
		$this->render('balance', $data);
	}
	
	/**
	 * 查看佣金支付历史
	 */
	public function actionHistory() {
		$arr = array(
			'criteria' => array(
				'condition' => 'loginid="'.Yii::app()->user->id.'"',
				'order' => 'pay_date DESC'
			)
		);
		$dataProvider = new CActiveDataProvider('Payment', $arr);
		$this->render('history', array('dataProvider' => $dataProvider));
	}
}